﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.CodeGeneration;
using Medianamik.Core.Sugar;
using Medianamik.UI.Controls;
using Telerik.Web.UI;

namespace Medianamik.UI.TypeManagement
{
    //TODO: Validation des champs

    /// <summary>
    /// Page listant les types
    /// </summary>
    public partial class TypeList : BasePage
    {
        #region Fields

        private Guid? _baseTypeID;

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            #region Param BaseTypeID

            string strBaseTypeId = Request.QueryString["basetypeid"];

            if (!String.IsNullOrEmpty(strBaseTypeId) && (!StringHelper.IsGuid(strBaseTypeId, ref _baseTypeID)
                || BaseType == null || !BaseType.IsInheritable))
            {
                Response.Redirect(ReturnURL);
            }

            #endregion

            TreeView.CurrentItemValue = BaseType == null ? "root" : BaseType.ID.ToString();

            if (!IsPostBack)
            {
                grdTypes.DataBind();
                LoadBreadcrumbs();
            }
        }

        /// <summary>
        /// Actions de type PostBack sur la grille des types
        /// </summary>
        /// <param name="e.CommandName">
        /// DeleteType = Suppression du Type
        /// </param>
        protected void grdTypes_ItemCommand(object sender, GridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteType":
                    var type = NodeTypeManager.GetNodeType(new Guid(e.CommandArgument.ToString()));
                    if (!type.HasNodes && !type.HasChildren)
                    {
                        NodeTypeManager.DeleteNodeType(type);
                        grdTypes.Rebind();
                        TreeView.Nodes.Clear();
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// Permet d'activer ou non le lien sur le nom du type afin de consulter les enfants
        /// Voir la propriété CanHaveChilds de NodeType
        /// Permet de gérer le boutton de supression
        /// </summary>
        //protected void grdTypes_ItemDataBound(object sender, GridItemEventArgs e)
        //{
        //    using (var gridDataItem = e.Item as GridDataItem)
        //    {
        //        if (gridDataItem != null)
        //        {
        //            var type = (NodeType)gridDataItem.DataItem;

        //            //Activation du lien sur le nom du type
        //            var link = e.Item.FindControl("lnkTypeName") as HyperLink;

        //            if (link != null)
        //            {
        //                link.Text = type.Name;
        //                link.Enabled = type.IsInheritable;

        //                if (link.Enabled)
        //                {
        //                    link.NavigateUrl = "TypeList.aspx?basetypeid=" + type.ID;
        //                }
        //            }

        //            var deleteBtn = e.Item.FindControl("btnDeleteType") as ImageButton;
        //            if (deleteBtn != null)
        //            {
        //                deleteBtn.Enabled = !type.HasNodes && !type.HasChildren;
        //            }
        //        }
        //    }

        //}

        protected string GetName(NodeType type)
        {
            return type.IsInheritable ? String.Format("<a href=\"{0}\">{1}</a>", 
                    "TypeList.aspx?basetypeid=" + type.ID, type.Name) : type.Name;
        }

        protected void grdTypes_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            grdTypes.DataSource = NodeTypeManager.GetChildTypes(_baseTypeID).Where(t => !t.IsManyToMany);
        }

        protected void lnkGenTable_Click(object sender, CommandEventArgs e)
        {
            var code = new CodeService();
            var t = NodeTypeManager.GetNodeType(new Guid((string)e.CommandArgument));
            code.DoTheMagic(t);
        }

        #endregion

        #region Properties

        private NodeType _baseType;
        public NodeType BaseType
        {
            get
            {
                if (_baseType == null && _baseTypeID.HasValue)
                {
                    _baseType = NodeTypeManager.GetNodeType(_baseTypeID.Value);
                }

                return _baseType;
            }
        }

        private string _addURL;
        public string AddURL
        {
            get
            {
                if (_addURL == null)
                {
                    _addURL = "Typemanagement.aspx";

                    if (_baseTypeID.HasValue)
                        _addURL += "?basetypeid=" + _baseTypeID;
                }

                return _addURL;
            }
        }

        private string _returnURL;
        public string ReturnURL
        {
            get
            {
                if (_returnURL == null)
                {
                    _returnURL = "TypeList.aspx";

                    if (BaseType != null && BaseType.ParentID.HasValue)
                        _returnURL += "?basetypeid=" + BaseType.ParentID.Value;
                }

                return _returnURL;
            }
        }

        #endregion

        #region Methods

        private void LoadBreadcrumbs()
        {
            var breadcrumbs = BaseType == null
                                         ? new List<Breadcrumb>()
                                         : new List<Breadcrumb>(BaseType.Breadcrumbs);

            breadcrumbs.Insert(0, new Breadcrumb(null,
                Resources("Medianamik_TypeManagement", "TypeManagement")));
            bctFilAriane.Breadcrumbs = breadcrumbs;
            bctFilAriane.DataBind();
        }

        #endregion

        #region TreeView

        protected void TreeView_NeedChildren(object sender, NeedChildrenEventArgs e)
        {
            Guid g;
            var parentId = StringHelper.IsGuid(e.ParentValue, out g)
                 ? g : default(Guid?);

            var types = NodeTypeManager.GetChildTypes(parentId)
                .Where(t => !t.IsManyToMany)
                .Select(t => new TreeItem(t.Name, t.ID.ToString(),
                    "TypeList.aspx?basetypeid=" + t.ID.ToString(),
                    null, t.HasChildren, t.IsInheritable));

            e.ChildNodes.AddRange(types.Cast<ITreeItem>());
        }

        protected void TreeView_NeedSelfAndParents(object sender, NeedSelfAndParentsEventArgs e)
        {
            Guid g;

            if (StringHelper.IsGuid(e.ItemValue, out g))
            {
                var types = NodeTypeManager.GetParentTypes(g, true)
                    .Where(t => !t.IsManyToMany)
                    .Select(t => new TreeItem(t.Name, t.ID.ToString(),
                        "TypeList.aspx?basetypeid=" + t.ID.ToString(),
                        null, t.HasChildren, true, t.Depth, true));

                e.Items.AddRange(types.Cast<ITreeItem>());
            }

            e.Items.Add(new TreeItem(Resources("Medianamik_TypeManagement", "TypeManagement"), 
                "root", "TypeList.aspx", null, true, true, int.MinValue, true));
        }

        #endregion
    }
}
